/*
 * 功能：负责处理与用户相关的HTTP请求
 * 作者：张杨(Sunny)
 * 日期： 2024/10/21 下午4:23
 */
package com.example.springboot.control;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * 用户控制器，提供用户相关的CRUD（创建读取更新删除）操作
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    // 新增用户信息
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    // 更新修改用户信息
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success();
    }

    // 删除指定 id 用户。
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            userService.deleteUserById(id, currentUser.getId());
        } else {
            throw new ServiceException("用户未登录");
        }
        return Result.success();
    }

    // 批量删除用户信息
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        userService.removeBatchByIds(ids);
        return Result.success();
    }

    // 根据 id 查询用户信息
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    // 分页查询用户信息
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String username, // 用户名
                               @RequestParam String name, // 姓名
                               @RequestParam String role, // 角色
                               @RequestParam String state) { // 状态，教练是所带学员数量，学员是学习进度
        Page<User> page = userService.selectByPage(pageNum, pageSize, username, name, role, state);
        return Result.success(page);
    }

    // 导出数据到本地 Excel 文件。
    @AuthAccess
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids,
                           @RequestParam(required = false) String role,
                           HttpServletResponse response) throws IOException {
        userService.exportData(username, name, ids, role, response);
    }

    // 导入数据到数据库
    @AuthAccess
    @PostMapping("/import")
    public Result importData(@RequestParam("file") MultipartFile file) {
        try {
            return userService.importData(file);
        } catch (IOException e) {
            return Result.error("导入失败");
        }
    }

    // 获取当前用户未读消息数
    @GetMapping("/getUnRead")
    public Result getUnRead(@RequestParam String username) {
        String unreadCount = userService.getUnRead(username);
        return Result.success(unreadCount);
    }
}
